package com.example.myxm.db;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.myxm.module.ExpenseBean;
import com.example.myxm.module.IncomeBean;
import com.example.myxm.module.ResultBean;
import com.example.myxm.module.UserBean;

import java.util.ArrayList;
import java.util.List;

/**
 * MyDBHelper 继承自 SQLiteOpenHelper，负责：
 *   1. 创建用户表（user）、收入表（income）、支出表（expense）；
 *   2. 所有的增删改查都返回 ResultBean<...>，其中 code=200 表示成功，400 表示失败。
 */
public class MyDBHelper extends SQLiteOpenHelper {

    private static final String TAG = "MyDBHelper";

    // 数据库名称与版本号
    private static final String DATABASE_NAME    = "xm.db";
    private static final int    DATABASE_VERSION = 1;

    // ============================ user 表定义 ============================
    public static final String TABLE_USER      = "user";
    public static final String COLUMN_ID       = "id";          // 用户自增主键
    public static final String COLUMN_USERNAME = "username";    // 用户名（唯一）
    public static final String COLUMN_PASSWORD = "password";    // 密码（示例中明文，生产请哈希）
    public static final String COLUMN_PHONE    = "phone";       // 手机号（唯一）

    // v2 版本起的建表语句（包含 phone 列）
    private static final String CREATE_TABLE_USER =
            "CREATE TABLE " + TABLE_USER + " ("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + COLUMN_USERNAME + " TEXT NOT NULL UNIQUE, "
                    + COLUMN_PASSWORD + " TEXT NOT NULL, "
                    + COLUMN_PHONE + " TEXT NOT NULL UNIQUE"
                    + ");";

    // ============================ income 表定义 ============================
    public static final String TABLE_INCOME      = "income";
    public static final String COLUMN_INCOME_ID  = "id";           // 收入自增主键
    public static final String COLUMN_INCOME_UID = "user_id";      // 外键，关联 user.id
    public static final String COLUMN_INCOME_AMT = "amount";       // 金额
    public static final String COLUMN_INCOME_DT  = "date";         // 日期（可存字符串，如 "2025-06-01"）
    public static final String COLUMN_INCOME_TYPE= "type";         // 类型（自定义，比如 "工资"、"投资" 等）
    public static final String COLUMN_INCOME_PAYER = "payer";      // 付款方
    public static final String COLUMN_INCOME_NOTE  = "note";       // 备注

    private static final String CREATE_TABLE_INCOME =
            "CREATE TABLE " + TABLE_INCOME + " ("
                    + COLUMN_INCOME_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + COLUMN_INCOME_UID + " INTEGER NOT NULL, "
                    + COLUMN_INCOME_AMT + " REAL NOT NULL, "
                    + COLUMN_INCOME_DT  + " TEXT NOT NULL, "
                    + COLUMN_INCOME_TYPE+ " TEXT, "
                    + COLUMN_INCOME_PAYER+ " TEXT, "
                    + COLUMN_INCOME_NOTE + " TEXT, "
                    + "FOREIGN KEY(" + COLUMN_INCOME_UID + ") REFERENCES "
                    + TABLE_USER + "(" + COLUMN_ID + ") ON DELETE CASCADE"
                    + ");";

    // ============================ expense 表定义 ============================
    public static final String TABLE_EXPENSE      = "expense";
    public static final String COLUMN_EXPENSE_ID  = "id";           // 支出自增主键
    public static final String COLUMN_EXPENSE_UID = "user_id";      // 外键，关联 user.id
    public static final String COLUMN_EXPENSE_AMT = "amount";       // 金额
    public static final String COLUMN_EXPENSE_DT  = "date";         // 日期
    public static final String COLUMN_EXPENSE_TYPE= "type";         // 类型（自定义，比如 "餐饮"、"交通" 等）
    public static final String COLUMN_EXPENSE_PAYEE = "payee";      // 收款方
    public static final String COLUMN_EXPENSE_NOTE  = "note";       // 备注

    private static final String CREATE_TABLE_EXPENSE =
            "CREATE TABLE " + TABLE_EXPENSE + " ("
                    + COLUMN_EXPENSE_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + COLUMN_EXPENSE_UID + " INTEGER NOT NULL, "
                    + COLUMN_EXPENSE_AMT + " REAL NOT NULL, "
                    + COLUMN_EXPENSE_DT  + " TEXT NOT NULL, "
                    + COLUMN_EXPENSE_TYPE+ " TEXT, "
                    + COLUMN_EXPENSE_PAYEE+ " TEXT, "
                    + COLUMN_EXPENSE_NOTE + " TEXT, "
                    + "FOREIGN KEY(" + COLUMN_EXPENSE_UID + ") REFERENCES "
                    + TABLE_USER + "(" + COLUMN_ID + ") ON DELETE CASCADE"
                    + ");";

    public MyDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * 数据库首次创建时调用：一次性创建 user/income/expense 三张表
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USER);
        db.execSQL(CREATE_TABLE_INCOME);
        db.execSQL(CREATE_TABLE_EXPENSE);
        Log.d(TAG, "onCreate: user/income/expense 三张表已创建");
    }

    /**
     * 当 DATABASE_VERSION 升级时调用。本示例直接 drop 三张表并重建，生产环境请谨慎，
     * 推荐使用 ALTER TABLE ... 逐步迁移以免丢失历史数据。
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "onUpgrade: 数据库版本从 " + oldVersion + " 升级到 " + newVersion + "，将重建所有表！");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_EXPENSE);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_INCOME);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
        onCreate(db);
    }

    // ============================ 用户相关操作（统一用 ResultBean 封装返回） ============================

    /**
     * 注册新用户（含用户名/密码/手机号），返回 ResultBean<UserBean>：
     *   - code=200、data=UserBean(刚插入并查询出的 id/username/phone) 表示注册成功
     *   - code=400、message="失败原因" 表示失败
     */
    public ResultBean<UserBean> registerUserBean(String username, String password, String phone) {
        if (username == null || password == null || phone == null
                || username.trim().isEmpty()
                || password.trim().isEmpty()
                || phone.trim().isEmpty()) {
            return new ResultBean<>("用户名、密码或手机号不能为空");
        }

        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = this.getWritableDatabase();

            // 1. 检查用户名是否已存在
            String queryUser = "SELECT " + COLUMN_ID
                    + " FROM " + TABLE_USER
                    + " WHERE " + COLUMN_USERNAME + " = ?";
            cursor = db.rawQuery(queryUser, new String[]{ username.trim() });
            if (cursor != null && cursor.moveToFirst()) {
                return new ResultBean<>("用户名已存在");
            }
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }

            // 2. 检查手机号是否已存在
            String queryPhone = "SELECT " + COLUMN_ID
                    + " FROM " + TABLE_USER
                    + " WHERE " + COLUMN_PHONE + " = ?";
            cursor = db.rawQuery(queryPhone, new String[]{ phone.trim() });
            if (cursor != null && cursor.moveToFirst()) {
                return new ResultBean<>("手机号已被注册");
            }
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }

            // 3. 插入用户记录
            ContentValues values = new ContentValues();
            values.put(COLUMN_USERNAME, username.trim());
            values.put(COLUMN_PASSWORD, password);
            values.put(COLUMN_PHONE, phone.trim());
            long newRowId = db.insert(TABLE_USER, null, values);
            if (newRowId == -1) {
                return new ResultBean<>("插入用户失败");
            }

            // 4. 查询刚插入的用户信息，封装成 UserBean
            String selectInserted = "SELECT " + COLUMN_ID + ", " + COLUMN_USERNAME + ", " + COLUMN_PHONE
                    + " FROM " + TABLE_USER
                    + " WHERE " + COLUMN_ID + " = ?";
            cursor = db.rawQuery(selectInserted, new String[]{ String.valueOf(newRowId) });
            if (cursor != null && cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
                String uname = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USERNAME));
                String uphone = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE));
                UserBean userBean = new UserBean(id, uname, uphone);
                return new ResultBean<>(userBean);
            } else {
                return new ResultBean<>("注册后查询用户失败");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * 登录校验：根据用户名+密码判断是否存在对应记录。
     * 返回 ResultBean<UserBean>：
     *   - code=200、data=UserBean(查询出的 id/username/phone) 表示登录成功
     *   - code=400、message="失败原因" 表示登录失败
     */
    public ResultBean<UserBean> loginUserBean(String username, String password) {
        if (username == null || password == null
                || username.trim().isEmpty()
                || password.trim().isEmpty()) {
            return new ResultBean<>("用户名或密码不能为空");
        }

        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = this.getReadableDatabase();
            String query = "SELECT " + COLUMN_ID + ", " + COLUMN_USERNAME + ", " + COLUMN_PHONE
                    + " FROM " + TABLE_USER
                    + " WHERE " + COLUMN_USERNAME + " = ?"
                    + "   AND " + COLUMN_PASSWORD + " = ?";
            cursor = db.rawQuery(query, new String[]{ username.trim(), password });
            if (cursor != null && cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
                String uname = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USERNAME));
                String uphone = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE));
                UserBean userBean = new UserBean(id, uname, uphone);
                return new ResultBean<>(userBean);
            } else {
                return new ResultBean<>("用户名或密码错误");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d(TAG, "loginUserBean: "+ e.toString());
            return new ResultBean<>("数据库异常：" + e.getMessage());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * 根据“用户名 + 手机号” 查询用户 ID (唯一键)。如果找不到，返回 ResultBean 空 data 加错误信息。
     * 返回 ResultBean<Integer>：code=200、data=userId 表示成功；code=400、message 表示失败
     */
    public ResultBean<Integer> getUserIdByUsernameAndPhoneBean(String username, String phone) {
        if (username == null || phone == null
                || username.trim().isEmpty() || phone.trim().isEmpty()) {
            return new ResultBean<>("用户名或手机号不能为空");
        }

        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = this.getReadableDatabase();
            String query = "SELECT " + COLUMN_ID
                    + " FROM " + TABLE_USER
                    + " WHERE " + COLUMN_ID + " = ?";
            cursor = db.rawQuery(query, new String[]{ username.trim(), phone.trim() });
            if (cursor != null && cursor.moveToFirst()) {
                int userId = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
                return new ResultBean<>(userId);
            } else {
                return new ResultBean<>("未找到对应用户");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }
    public ResultBean<UserBean> getUserIdBean(int userUid) {
        if (userUid < 0) {
            return new ResultBean<>("userUid 无效");
        }

        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = this.getReadableDatabase();
            String query = "SELECT "
                    + COLUMN_ID + ", "
                    + COLUMN_USERNAME + ", "
                    + COLUMN_PHONE + ", "
                    + COLUMN_PASSWORD
                    + " FROM " + TABLE_USER
                    + " WHERE " + COLUMN_ID + " = ?";
            cursor = db.rawQuery(query, new String[]{String.valueOf(userUid)});

            if (cursor != null && cursor.moveToFirst()) {
                // 构造一个新的 UserBean 对象，并将查询到的字段赋值
                UserBean user = new UserBean();
                int    idxId       = cursor.getColumnIndexOrThrow(COLUMN_ID);
                int    idxUsername = cursor.getColumnIndexOrThrow(COLUMN_USERNAME);
                int    idxPhone    = cursor.getColumnIndexOrThrow(COLUMN_PHONE);
                int    idxPassword = cursor.getColumnIndexOrThrow(COLUMN_PASSWORD);

                user.setId(cursor.getInt(idxId));
                user.setUsername(cursor.getString(idxUsername));
                user.setPhone(cursor.getString(idxPhone));
                user.setPassword(cursor.getString(idxPassword));

                return new ResultBean<>(user);
            } else {
                return new ResultBean<>("未找到对应用户");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            // 不要在这里 close(db)，SQLiteOpenHelper 会管理连接的生命周期
        }
    }

    public ResultBean<Integer> updatePassword(int userUid, String username, String newPassword) {
        if (userUid < 0) {
            return new ResultBean<>("userUid 无效");
        }
        if (username.trim().isEmpty()) {
            return new ResultBean<>("用户名不能为空");
        }
        if (newPassword.trim().isEmpty()) {
            return new ResultBean<>("新密码不能为空");
        }

        SQLiteDatabase db = null;
        try {
            db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(COLUMN_PASSWORD, newPassword);

            // WHERE id = ? AND username = ?
            String whereClause = COLUMN_ID + " = ? AND " + COLUMN_USERNAME + " = ?";
            String[] whereArgs = new String[]{String.valueOf(userUid), username};

            int rowsAffected = db.update(TABLE_USER, values, whereClause, whereArgs);
            if (rowsAffected > 0) {
                return new ResultBean<>(200);
            } else {
                return new ResultBean<>("更新失败：未找到匹配的用户或用户名不符");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }

    // ============================ 收入相关操作 ============================

    /**
     * 新增一条收入记录，返回 ResultBean<IncomeBean>：
     *   - code=200、data=IncomeBean(插入后的所有字段，包括自增 id) 表示成功
     *   - code=400、message 表示失败原因
     */
    public ResultBean<IncomeBean> addIncomeBean(int userId,
                                                double amount,
                                                String date,
                                                String type,
                                                String payer,
                                                String note) {
        if (userId < 0 || date == null || date.trim().isEmpty()) {
            return new ResultBean<>("userId 或 date 无效");
        }
        SQLiteDatabase db = null;
        try {
            db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(COLUMN_INCOME_UID, userId);
            values.put(COLUMN_INCOME_AMT, amount);
            values.put(COLUMN_INCOME_DT, date.trim());
            values.put(COLUMN_INCOME_TYPE, type);
            values.put(COLUMN_INCOME_PAYER, payer);
            values.put(COLUMN_INCOME_NOTE, note);
            long newRowId = db.insert(TABLE_INCOME, null, values);
            if (newRowId == -1) {
                return new ResultBean<>("插入收入记录失败");
            }

            // 查询刚插入的那条记录
            String selectInserted = "SELECT * FROM " + TABLE_INCOME
                    + " WHERE " + COLUMN_INCOME_ID + " = ?";
            Cursor cursor = db.rawQuery(selectInserted, new String[]{ String.valueOf(newRowId) });
            if (cursor != null && cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_INCOME_ID));
                double amt = cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_INCOME_AMT));
                String dt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_DT));
                String tp = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_TYPE));
                String py = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_PAYER));
                String nt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_NOTE));
                IncomeBean bean = new IncomeBean(id, userId, amt, dt, tp, py, nt);
                cursor.close();
                return new ResultBean<>(bean);
            } else {
                if (cursor != null) cursor.close();
                return new ResultBean<>("插入后查询收入记录失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }

    /**
     * 按 userId 查询该用户所有收入记录，按 date 倒序排列。
     * 返回 ResultBean<List<IncomeBean>>：
     *   - code=200、data=List<IncomeBean>（即使为空列表，也算成功）
     *   - code=400、message 表示失败（如 userId 无效或数据库异常）
     */
    public ResultBean<List<IncomeBean>> getIncomesByUserBean(int userId) {
        if (userId < 0) {
            return new ResultBean<>("userId 无效");
        }
        SQLiteDatabase db = null;
        Cursor cursor = null;
        List<IncomeBean> list = new ArrayList<>();
        try {
            db = this.getReadableDatabase();
            String query = "SELECT * FROM " + TABLE_INCOME
                    + " WHERE " + COLUMN_INCOME_UID + " = ?"
                    + " ORDER BY " + COLUMN_INCOME_DT + " DESC";
            cursor = db.rawQuery(query, new String[]{ String.valueOf(userId) });
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_INCOME_ID));
                    double amt = cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_INCOME_AMT));
                    String dt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_DT));
                    String tp = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_TYPE));
                    String py = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_PAYER));
                    String nt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_INCOME_NOTE));
                    list.add(new IncomeBean(id, userId, amt, dt, tp, py, nt));
                }
            }
            return new ResultBean<>(list);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    // ============================ 支出相关操作 ============================

    /**
     * 新增一条支出记录，返回 ResultBean<ExpenseBean>：
     *   - code=200、data=ExpenseBean(插入后的所有字段，包括自增 id) 表示成功
     *   - code=400、message 表示失败原因
     */
    public ResultBean<ExpenseBean> addExpenseBean(int userId,
                                                  double amount,
                                                  String date,
                                                  String type,
                                                  String payee,
                                                  String note) {
        if (userId < 0 || date == null || date.trim().isEmpty()) {
            return new ResultBean<>("userId 或 date 无效");
        }
        SQLiteDatabase db = null;
        try {
            db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(COLUMN_EXPENSE_UID, userId);
            values.put(COLUMN_EXPENSE_AMT, amount);
            values.put(COLUMN_EXPENSE_DT, date.trim());
            values.put(COLUMN_EXPENSE_TYPE, type);
            values.put(COLUMN_EXPENSE_PAYEE, payee);
            values.put(COLUMN_EXPENSE_NOTE, note);
            long newRowId = db.insert(TABLE_EXPENSE, null, values);
            if (newRowId == -1) {
                return new ResultBean<>("插入支出记录失败");
            }

            // 查询刚插入的那条记录
            String selectInserted = "SELECT * FROM " + TABLE_EXPENSE
                    + " WHERE " + COLUMN_EXPENSE_ID + " = ?";
            Cursor cursor = db.rawQuery(selectInserted, new String[]{ String.valueOf(newRowId) });
            if (cursor != null && cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_ID));
                double amt = cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_AMT));
                String dt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_DT));
                String tp = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_TYPE));
                String py = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_PAYEE));
                String nt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_NOTE));
                ExpenseBean bean = new ExpenseBean(id, userId, amt, dt, tp, py, nt);
                cursor.close();
                return new ResultBean<>(bean);
            } else {
                if (cursor != null) cursor.close();
                return new ResultBean<>("插入后查询支出记录失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }

    /**
     * 按 userId 查询该用户所有支出记录，按 date 倒序排列。
     * 返回 ResultBean<List<ExpenseBean>>：
     *   - code=200、data=List<ExpenseBean>（即使为空列表，也算成功）
     *   - code=400、message 表示失败（如 userId 无效或数据库异常）
     */
    public ResultBean<List<ExpenseBean>> getExpensesByUserBean(int userId) {
        if (userId < 0) {
            return new ResultBean<>("userId 无效");
        }
        SQLiteDatabase db = null;
        Cursor cursor = null;
        List<ExpenseBean> list = new ArrayList<>();
        try {
            db = this.getReadableDatabase();
            String query = "SELECT * FROM " + TABLE_EXPENSE
                    + " WHERE " + COLUMN_EXPENSE_UID + " = ?"
                    + " ORDER BY " + COLUMN_EXPENSE_DT + " DESC";
            cursor = db.rawQuery(query, new String[]{ String.valueOf(userId) });
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_ID));
                    double amt = cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_AMT));
                    String dt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_DT));
                    String tp = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_TYPE));
                    String py = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_PAYEE));
                    String nt = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EXPENSE_NOTE));
                    list.add(new ExpenseBean(id, userId, amt, dt, tp, py, nt));
                }
            }
            return new ResultBean<>(list);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    // ============================ 可选的删除/更新示例 ============================

    /**
     * 删除某用户的所有收入记录，返回 ResultBean<Integer>（被删除的行数）。
     */
    public ResultBean<Integer> deleteIncomesByUserBean(int userId) {
        if (userId < 0) {
            return new ResultBean<>("userId 无效");
        }
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            int rows = db.delete(TABLE_INCOME, COLUMN_INCOME_UID + " = ?", new String[]{ String.valueOf(userId) });
            return new ResultBean<>(rows);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }

    public ResultBean<Integer> deleteIncomesByUserBean(int userId,IncomeBean incomeBean){
        if (userId < 0 || incomeBean == null || incomeBean.getId() < 0) {
            return new ResultBean<>("userId 或 incomeBean 无效");
        }
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            int rows = db.delete(TABLE_INCOME, COLUMN_INCOME_UID + " = ? AND " + COLUMN_INCOME_ID + " = ?",
                    new String[]{ String.valueOf(userId), String.valueOf(incomeBean.getId()) });
            return new ResultBean<>(rows);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }
    /**
     * 删除某用户的所有支出记录，返回 ResultBean<Integer>（被删除的行数）。
     */
    public ResultBean<Integer> deleteExpensesByUserBean(int userId) {
        if (userId < 0) {
            return new ResultBean<>("userId 无效");
        }
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            int rows = db.delete(TABLE_EXPENSE, COLUMN_EXPENSE_UID + " = ?", new String[]{ String.valueOf(userId) });
            return new ResultBean<>(rows);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }
    /**
     * 删除某用户的所有支出记录，返回 ResultBean<Integer>（被删除的行数）。
     */
    public ResultBean<Integer> deleteExpensesByUserBean(int userId,ExpenseBean expenseBean) {
        if (userId < 0 || expenseBean == null || expenseBean.getId() < 0) {
            return new ResultBean<>("userId 或 incomeBean 无效");
        }
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            int rows = db.delete(TABLE_INCOME, COLUMN_INCOME_UID + " = ? AND " + COLUMN_INCOME_ID + " = ?",
                    new String[]{ String.valueOf(userId), String.valueOf(expenseBean.getId()) });
            return new ResultBean<>(rows);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }

    /**
     * 更新某条收入记录（只更新 amount/type/payer/note），返回 ResultBean<Boolean>：
     *   - code=200、data=true 表示成功
     *   - code=400、message 表示失败原因
     */
    public ResultBean<Boolean> updateIncomeBean(int incomeId,
                                                double amount,
                                                String type,
                                                String payer,
                                                String note) {
        if (incomeId < 0) {
            return new ResultBean<>("incomeId 无效");
        }
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put(COLUMN_INCOME_AMT, amount);
            cv.put(COLUMN_INCOME_TYPE, type);
            cv.put(COLUMN_INCOME_PAYER, payer);
            cv.put(COLUMN_INCOME_NOTE, note);
            int rows = db.update(TABLE_INCOME, cv, COLUMN_INCOME_ID + " = ?", new String[]{ String.valueOf(incomeId) });
            if (rows > 0) {
                return new ResultBean<>(true);
            } else {
                return new ResultBean<>("未找到该条收入记录或更新失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }

    /**
     * 更新某条支出记录（只更新 amount/type/payee/note），返回 ResultBean<Boolean>：
     *   - code=200、data=true 表示成功
     *   - code=400、message 表示失败原因
     */
    public ResultBean<Boolean> updateExpenseBean(int expenseId,
                                                 double amount,
                                                 String type,
                                                 String payee,
                                                 String note) {
        if (expenseId < 0) {
            return new ResultBean<>("expenseId 无效");
        }
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put(COLUMN_EXPENSE_AMT, amount);
            cv.put(COLUMN_EXPENSE_TYPE, type);
            cv.put(COLUMN_EXPENSE_PAYEE, payee);
            cv.put(COLUMN_EXPENSE_NOTE, note);
            int rows = db.update(TABLE_EXPENSE, cv, COLUMN_EXPENSE_ID + " = ?", new String[]{ String.valueOf(expenseId) });
            if (rows > 0) {
                return new ResultBean<>(true);
            } else {
                return new ResultBean<>("未找到该条支出记录或更新失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultBean<>("数据库异常：" + e.getMessage());
        }
    }
}
